package com.gexiaobao.pigeon.ui.fragment.mine.banking

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.QueryBalanceResponse
import com.gexiaobao.pigeon.app.model.param.MemberTransferParam
import com.gexiaobao.pigeon.app.model.param.PayParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentAccountTransferBinding
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.ui.view.MyTextWatcher
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 19:41
 * @Describe    : 转账
 */
class FragmentAccountTransfer: BaseFragment<MineBankingViewModel, FragmentAccountTransferBinding>() {

    private var mOrderId: Int = 0
    private var payDialog: RxPayDialog? = null
    private var isResendCode: Boolean = false

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.includeBar.toolbar.initClose("转账") {
            nav().navigateUp()
        }
        val mData = arguments?.getParcelable<QueryBalanceResponse>(Constant.DATA_BEAN)
        if (mData != null) {
            mViewModel.availableBalances.set(SettingUtil.div(mData.allAmount - mData.freezenAmount, 100.00, 2).toString())
        }
        mDatabind.etInvestMoney.addTextChangedListener(MyTextWatcher(2, mDatabind.etInvestMoney))
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.investMoneyCommit) {
            when (it.id) {
                R.id.invest_money_commit -> {
                    isResendCode = false
                    applyTransfer()
                }
            }
        }
    }

    private fun applyTransfer() {
        var payFor = 0
        if (mViewModel.transferMoney.get().isNotEmpty()) {
            payFor = (mViewModel.transferMoney.get().toDouble() * 100).toInt()
        }
        when {
            mViewModel.payeeName.get().isEmpty() -> showMessage("收款人姓名不能为空")
            mViewModel.payeePhone.get().isEmpty() -> showMessage("收款人电话不能为空")
            !Util.isTelPhoneNumber(mViewModel.payeePhone.get()) -> showMessage(resources.getString(R.string.user_phone_number_wrong))
            payFor <= 0 -> showMessage("金额不能为空")
            else -> {
                val body = MemberTransferParam(
                    money = payFor,
                    toUserName = mViewModel.payeeName.get(),
                    toUserPhone = mViewModel.payeePhone.get()
                )
                showLoading(getString(R.string.loading))
                mViewModel.memberTransfer(body)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        mViewModel.payResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                payPassDialog?.dismiss()
                if (payDialog != null && payDialog!!.isShowing)
                    payDialog?.showBottomView()
                workWithResponseData()
            }, {
                payDialog?.dismiss()
                RxToast.showToast(it.msg)
            })
        }

        mViewModel.memTransferResult.observe(viewLifecycleOwner) { resultState ->
            dismissLoading()
            parseState(resultState, {
                mOrderId = it.orderId
                if (!isResendCode) {
                    showPayDialog()
                }
            }, {
                RxToast.showToast(it.msg)
            })
        }
    }

    @SuppressLint("SetTextI18n")
    private fun workWithResponseData() {
        payDialog?.showBottomView()
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent("转账成功")
        job = countDownCoroutines(3, {
            payDialog?.sureView?.text = "($it)秒后自动返回"
        }, {
            payDialog?.dismiss()
            onBackToMineBankPage()
            job?.cancel()
        }, lifecycleScope)
        payDialog?.setCancelBtnContent("立即返回")
    }

    private fun onBackToMineBankPage() {
        setFragmentResult("RechargeIsOk", Bundle().apply {
            putBoolean("isOK", true)
        })
        nav().navigateUp()
    }

    var payPassDialog: PayPassDialog? = null
    private fun showPayDialog() {
        payPassDialog = PayPassDialog(context)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                isResendCode = true
                val body = MemberTransferParam(
                    money = (mViewModel.transferMoney.get().toDouble() * 100).toInt(),
                    toUserName = mViewModel.payeeName.get(),
                    toUserPhone = mViewModel.payeePhone.get()
                )
                mViewModel.memberTransfer(body)
            }

            override fun onPassFinish(verifyCode: String?) {
//                payPassDialog?.dismiss()
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val body = PayParam(mOrderId, verifyCode.toString())
                    mViewModel.commitPay(body)
                }, lifecycleScope)

            }
        })
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(context)
        payDialog!!.loadingDialog()
        payDialog!!.setCancelListener {
            try {
                job?.cancel()
                payDialog!!.dismiss()
            } catch (_: Exception) {
            }
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }
}